<template>
	<div class="mail_view">
		<h1>站内信</h1>
		<a-collapse
			class="mail_list"
			:default-active-key="[1]"
			:expand-icon-position="position"
			@change="readMail"
			accordion
		>
			<a-collapse-item
				v-for="item in emailPage"
				:key="item._id"
				:header="item.title"
			>
				<div>发件人:{{ item.fromUser }}</div>
				<div>{{ item.context }}</div>
				<template #extra>
					<div>
						发送于:{{ item.sendDate }}
						<a-badge status="danger" v-if="!item.isRead" />
					</div>
				</template>
			</a-collapse-item>
		</a-collapse>
		<a-pagination @change="pageChange" :total="total" show-total />
	</div>
</template>

<script setup>
import usersApi from '../../api/users'
const emailList = ref([])
const emailPage = ref([])
const position = ref('right')
const mails = {}
const total = ref('0')
// 默认获取站内信内容
;(function getMailList() {
	usersApi.getMailList().then(res => {
		emailList.value = res.find_mail
		// 获取总数
		total.value = res.find_mail.length
		// 将id作为key来存储单一邮件对象
		res.find_mail.forEach(x => {
			mails[x._id] = x
		})
		// 设置好初始分页
		pageChange(1)
	})
})()

// 阅读站内信时触发
function readMail(activeKey) {
	if (activeKey.length !== 0) {
		mails[activeKey[0]].isRead
			? ''
			: usersApi.readMail(activeKey).then(res => {
					AMessage.success(res.data.message)
					mails[activeKey[0]].isRead = true
			  })
	}
}
// 更改页数时 截取新的内容
function pageChange(size) {
	size *= 10
	emailPage.value = emailList.value.slice(size - 10, size)
}
</script>

<style lang="scss" scoped>
.mail_view {
	width: 1280px;
	margin: 0 auto;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;

	& > * + * {
		margin-top: var(--normal-distance);
	}
	h1 {
		color: var(--fc-bg);
	}
	.mail_list {
		width: 100%;
	}
}
:deep(.arco-collapse-item-header.arco-collapse-item-header-right) {
	background-color: var(--main-2-bg);
}
:deep(.arco-collapse-item-content.arco-collapse-item-content-expend) {
	background-color: var(--main-bg);
}
</style>
